/*
 * Copyright © Yan Zhenjie. All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jshongli.myapplication.common.adapter;

import android.Manifest;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;


import com.jshongli.myapplication.GlideApp;
import com.jshongli.myapplication.R;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.album.impl.OnItemClickListener;
import com.yanzhenjie.album.util.AlbumUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class PhotoPickerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final static int TYPE_ADD = 3;
    private static final int REQUEST_CAMERA_PERMISSIONS = 1;
    private String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO};

    private LayoutInflater mInflater;
    private OnItemClickListener mItemClickListener;

    private int maxCount;

    private List<AlbumFile> mAlbumFiles;
    private Activity mActivity;

    public PhotoPickerAdapter(Activity activity, List<AlbumFile> mAlbumFiles, int maxCount, OnItemClickListener itemClickListener) {
        this.mActivity = activity;
        this.mInflater = LayoutInflater.from(activity);
        this.maxCount = maxCount;
        this.mItemClickListener = itemClickListener;
        this.mAlbumFiles = mAlbumFiles;
        padding = dip2Px(8);
    }

    public List<AlbumFile> getData() {
        return mAlbumFiles;
    }

    public void notifyDataSetChanged(List<AlbumFile> imagePathList) {
        this.mAlbumFiles = imagePathList;
        super.notifyDataSetChanged();
    }

    public int dip2Px(int dip) {
        // px/dip = density;
        float density = mActivity.getResources().getDisplayMetrics().density;
        int px = (int) (dip * density + .5f);
        return px;
    }

    int padding;

    @Override
    public int getItemViewType(int position) {
        if (mAlbumFiles != null && mAlbumFiles.size() > 0) {
            if (mAlbumFiles.size() < maxCount) {
                if (position < mAlbumFiles.size()) {
                    AlbumFile albumFile = mAlbumFiles.get(position);
                    if (albumFile.getMediaType() == AlbumFile.TYPE_IMAGE) {
                        return AlbumFile.TYPE_IMAGE;
                    } else {
                        return AlbumFile.TYPE_VIDEO;
                    }
                } else {
                    return TYPE_ADD;
                }
            } else {
                AlbumFile albumFile = mAlbumFiles.get(position);
                if (albumFile.getMediaType() == AlbumFile.TYPE_IMAGE) {
                    return AlbumFile.TYPE_IMAGE;
                } else {
                    return AlbumFile.TYPE_VIDEO;
                }
            }
        } else {
            return TYPE_ADD;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case AlbumFile.TYPE_IMAGE: {
                return new ImageViewHolder(mInflater.inflate(R.layout.item_content_image, parent, false), mItemClickListener);
            }
            case AlbumFile.TYPE_VIDEO:
            case TYPE_ADD:
            default: {
                return new VideoViewHolder(mInflater.inflate(R.layout.item_content_video, parent, false), mItemClickListener);
            }
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        RequestOptions requestOptions = new RequestOptions();
        requestOptions
                .centerCrop()
                .placeholder(R.drawable.icon_propser_add)
                .error(R.drawable.icon_propser_add);

        int viewType = getItemViewType(position);
        switch (viewType) {
            case AlbumFile.TYPE_IMAGE: {
                ((ImageViewHolder) holder).setData(mAlbumFiles.get(position), position);
                break;
            }
            case AlbumFile.TYPE_VIDEO: {
                ((VideoViewHolder) holder).setData(mAlbumFiles.get(position), position);
                break;
            }
            case TYPE_ADD:
                ((VideoViewHolder) holder).mRlVideo.setPadding(padding, padding, padding, padding);
                ((VideoViewHolder) holder).deleteBtn.setVisibility(View.GONE);
                Glide.with(mActivity)
                        .load("")
                        .apply(requestOptions)
                        .thumbnail(0.1f)
                        .into(((VideoViewHolder) holder).mIvImage);
                ((VideoViewHolder) holder).mIvImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 视频拍摄
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                            cameraPermission();
//                        } else {
//                            ToastUtils.show(mActivity, "安卓版本5.0以上才能使用该功能");
//                        }
                        selectImage();
                    }
                });
                break                                                ;
        }


    }

    private OnItemClickListener mListener;// 声明自定义的接

    @Override
    public int getItemCount() {
        if (mAlbumFiles != null && mAlbumFiles.size() < maxCount) {
            return mAlbumFiles.size() + 1;
        } else {
            return maxCount;
        }

    }

    private class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private final int itemSize;
        private final OnItemClickListener mItemClickListener;

        private ImageView mIvImage;
        private View deleteBtn;

        ImageViewHolder(View itemView, OnItemClickListener itemClickListener) {
            super(itemView);

            this.itemSize = itemView.getLayoutParams().width;
            this.mItemClickListener = itemClickListener;

            mIvImage = itemView.findViewById(R.id.iv_album_content_image);
            deleteBtn = itemView.findViewById(R.id.v_delete);

            itemView.setOnClickListener(this);
        }

        public void setData(AlbumFile albumFile, final int position) {
//            if (new File(albumFile.getPath()).exists()) {
                Album.getAlbumConfig().
                        getAlbumLoader().
                        loadAlbumFile(mIvImage, albumFile, itemSize, itemSize);
//            } else {
//                GlideApp.with(mActivity)
//                        .load(albumFile.getPath())
//                        .into(mIvImage);
//            }

            GlideApp.with(mActivity)
                    .load(albumFile.getPath())
                    .into(mIvImage);

            mIvImage.setPadding(padding, padding, padding, padding);
            deleteBtn.setVisibility(View.VISIBLE);
            deleteBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mAlbumFiles.remove(position);
                    notifyDataSetChanged();
                    // 删除图片接口
                    if (mListener != null) {
                        mListener.onItemClick(v, position);
                    }
                }
            });
        }

        @Override
        public void onClick(View v) {
            if (mItemClickListener != null) {
                mItemClickListener.onItemClick(v, getAdapterPosition());
            }
        }
    }

    private class VideoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private final int itemSize;
        private final OnItemClickListener mItemClickListener;

        private RelativeLayout mRlVideo;
        private ImageView mIvImage;
        private TextView mTvDuration;
        private View deleteBtn;

        VideoViewHolder(View itemView, OnItemClickListener itemClickListener) {
            super(itemView);

            this.itemSize = itemView.getLayoutParams().width;
            this.mItemClickListener = itemClickListener;

            mRlVideo = itemView.findViewById(R.id.rl_video);
            mIvImage = itemView.findViewById(com.yanzhenjie.album.R.id.iv_album_content_image);
            mTvDuration = itemView.findViewById(com.yanzhenjie.album.R.id.tv_duration);
            deleteBtn = itemView.findViewById(R.id.v_delete);

            itemView.setOnClickListener(this);
        }

        void setData(AlbumFile albumFile, final int position) {
            if (new File(albumFile.getPath()).exists()) {
                Album.getAlbumConfig().
                        getAlbumLoader().
                        loadAlbumFile(mIvImage, albumFile, itemSize, itemSize);
            } else {
                GlideApp.with(mActivity)
                        .load(albumFile.getPath())
                        .into(mIvImage);
            }
            mRlVideo.setPadding(padding, padding, padding, padding);
            mTvDuration.setText(AlbumUtils.convertDuration(albumFile.getDuration()));

            deleteBtn.setVisibility(View.VISIBLE);
            deleteBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mAlbumFiles.remove(position);
                    notifyDataSetChanged();
                    // 删除图片接口
                    if (mListener != null) {
                        mListener.onItemClick(v, position);
                    }
                }
            });
        }

        @Override
        public void onClick(View v) {
            if (mItemClickListener != null) {
                mItemClickListener.onItemClick(v, getAdapterPosition());
            }
        }
    }


    public void onitemdelete(OnItemClickListener clickListener) {

        mListener = clickListener;
    }

    /**
     * Select picture, from album.
     */
    private void selectImage() {
        Album.image(mActivity)
                .multipleChoice()
                .camera(true)
                .columnCount(2)
                .selectCount(maxCount != 0 ? maxCount : 1)
                .checkedList((ArrayList<AlbumFile>) mAlbumFiles)
                .widget(
                        Widget.newDarkBuilder(mActivity)
                                .statusBarColor(ContextCompat.getColor(mActivity, R.color.colorPrimary))
                                .toolBarColor(ContextCompat.getColor(mActivity, R.color.colorPrimary))
                                .title("选择图片")
                                .build()
                )
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                        mAlbumFiles = result;
                        Log.e("TAG", "onAction: size " + mAlbumFiles.size());
                        notifyDataSetChanged(mAlbumFiles);
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(int requestCode, @NonNull String result) {
                        ToastUtils.show(mActivity, "取消选择");
                    }
                })
                .start();
    }

    @AfterPermissionGranted(REQUEST_CAMERA_PERMISSIONS)
    private void cameraPermission() {
        if (!EasyPermissions.hasPermissions(mActivity, perms)) {
            EasyPermissions.requestPermissions(mActivity, "应用需要获取拍摄照片或录制视频,和读写的权限。",
                    REQUEST_CAMERA_PERMISSIONS, perms);
        } else {
//            Camera2RecordActivity.startForResult(mActivity);
        }
    }

}
